package com.lenovo.leos.filebrowser.netdisk;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.Activity.OnTitleIconClickListener;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.engine.util.FileUtil;
import com.lenovo.leos.filebrowser.engine.util.MimeTypeParser;
import com.lenovo.leos.filebrowser.engine.util.MimeTypes;
import com.lenovo.leos.letools.db.AllUploadTaskEntity;
import com.lenovo.leos.letools.db.FileDownloadEntity;
import com.lenovo.leos.letools.db.FileDownloadService;
import com.lenovo.leos.letools.db.FileUploadEntity;
import com.lenovo.leos.letools.db.FileUploadService;
import com.lenovo.leos.letools.domain.ForStartTaskEntity;
import com.lenovo.leos.letools.lenovodata.DownLoadServer;
import com.lenovo.leos.letools.lenovodata.DownLoadThread;
import com.lenovo.leos.letools.lenovodata.UploadServer;
import com.lenovo.leos.letools.lenovodata.UploadThread;
import com.lenovo.leos.letools.lenovodata.DownLoadServer.TotalFilelenPreDir;
import com.lenovo.leos.letools.utils.Constants;

public class TaskManagerActivity extends Activity implements
		OnTitleIconClickListener, OnClickListener {

	private static final String TAG = "TaskManagerActivity";
	private static final boolean TAG_FLAG = true;

	private String projectState;
	private static final String ZIP_MIMETYPE = "compressor/zip";
	private static MimeTypes mMimeTypes = null;
	private Button allCancelBtn;
	private LinearLayout downloadcontainer;
	// private DownLoadServer mFileSyncService;
	// private UploadServer mFileSyncService;
	private LayoutInflater inflater;
	private static final int style_download_file = 0;// 下载文件
	private static final int style_download_dir = 1;// 下载文件夹
	private static final int style_upload_file = 2;// 上传文件
	private static final int style_upload_dir = 3;// 上传文件夹
	private List<String> fileAndDirList;// 通过Intent传递的文件夹或文件的上传或下载的信息
	private Map<String, ForStartTaskEntity> fstes;// 用于从其他Activity跳转到本Activity后自动开启任务
	private static final int DOWNLOAD_OVER = 1;
	private Handler mHandler = new Handler();
	private DownLoadServer downLoadServer;
	private UploadServer uploadServer;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_manager);
		downLoadServer = DownLoadServer.getInstance(this);
		uploadServer = UploadServer.getInstance(this);
		setTitle(R.string.task_manager);
		init();
		dynicCreateProgressBar();
		mFileSyncService.showNotify();
		// for(int i=0;i<5;i++){
		// Log.d(TAG,"########################## TaskManagerActivity onCreate ");
		// }

	}

	FileSyncService mFileSyncService;


	public void init() {
		allCancelBtn = (Button) findViewById(R.id.allCancelBtn);
		allCancelBtn.setOnClickListener(this);
		projectState = getIntent().getStringExtra("projectState");
		fileAndDirList = this.getIntent().getStringArrayListExtra(
				"fileAndDirList");
		// mFileSyncService = new DownLoadServer(this);
		// mFileSyncService = new UploadServer(this);
		downloadcontainer = (LinearLayout) findViewById(R.id.downloadcontainer);
		inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mFileSyncService = FileSyncServiceManager.getInstance(this).doBindService();
		fstes = new HashMap<String, ForStartTaskEntity>();
		initMimeTypes();
	}

	public void dynicCreateProgressBar() {
		// 从数据库中得到所有的下载任务
		List<FileDownloadEntity> fileTasks = mFileSyncService.getFileLoadTask();
		// 从数据库中得到所有的文件夹下载任务
		Map<String, List<FileDownloadEntity>> dirTasks = mFileSyncService
				.getDirLoadTask();
		// 从数据库中得到所有的文件夹和文件上传任务
		AllUploadTaskEntity allUploadTask = mFileSyncService.getAllTask();

		if (fileTasks.size() == 0 && dirTasks.size() == 0
				&& allUploadTask.getFileTasks().size() == 0
				&& allUploadTask.getDirTasks().size() == 0) {// 没有上传或下载任务
			Toast.makeText(this, getString(R.string.no_task),
					Toast.LENGTH_SHORT).show();
			allCancelBtn.setEnabled(false);
			return;
		} else {
			if (fileTasks.size() != 0)
				downloadDynicCreateProgressBarByFile(fileTasks);

			if (dirTasks.size() != 0)
				downloadDynicCreateProgressBarByDir(dirTasks);

			if (allUploadTask.getFileTasks().size() != 0)
				uploadDynicCreateProgressBarByFile(allUploadTask.getFileTasks());

			if (allUploadTask.getDirTasks().size() != 0)
				uploadDynicCreateProgressBarByDir(allUploadTask.getDirTasks());
		}
		if (fstes != null && fileAndDirList != null) {
			for (String fileOrDirPath : fileAndDirList) {
				ForStartTaskEntity fste = fstes.get(fileOrDirPath);
				if (fstes == null)
					return;
				if (TAG_FLAG) {
					Log.d(TAG, "================" + fstes);
				}
				fste.getStartLv().setVisibility(View.GONE);
				fste.getPauseLv().setVisibility(View.VISIBLE);
				switch (fste.getStyle()) {
				case style_download_file:
					mFileSyncService.startDownLoadThreadByFile(fileOrDirPath,
							fste.getPb(), fste.getDownTitle(),
							fste.getFileLen());
					break;
				case style_download_dir:
					mFileSyncService.startDownLoadThreadByDir(fileOrDirPath,
							fste.getPb(), fste.getDownTitle(),
							fste.getFileLen());
					break;
				case style_upload_file:
					mFileSyncService.startUpload(fileOrDirPath, fste.getPb(),
							fste.getDownTitle(), fste.getFileLen());
					break;
				case style_upload_dir:
					mFileSyncService.startDirUpload(fileOrDirPath,
							fste.getPb(), fste.getDownTitle(),
							fste.getFileLen());
					break;
				default:
					break;
				}
			}
		}
	}

	// 创建单个文件下载的进度条
	public void downloadDynicCreateProgressBarByFile(
			List<FileDownloadEntity> downloadThreadTasks) {
		// 遍历数据库中任务
		for (FileDownloadEntity enty : downloadThreadTasks) {
			String fileOrDirName = (new File(enty.getFileWholePath()))
					.getName();
			createProgressBar(style_download_file, fileOrDirName,
					enty.getDownpath(), enty.getFilelen(),
					enty.getDownlength(), enty.getLoadover(),
					enty.getIsloading());
		}
	}

	// 创建文件夹下载的进度条
	public void downloadDynicCreateProgressBarByDir(
			Map<String, List<FileDownloadEntity>> dirTasks) {
		Set<Entry<String, List<FileDownloadEntity>>> entrys = dirTasks
				.entrySet();
		for (Entry<String, List<FileDownloadEntity>> entry : entrys) {
			String dirid = entry.getKey();
			int currentTotalLen = 0;
			int totalFileLen = 0;
			int isLoading = 0;
			int isloadover = Constants.loadover_yes;
			String topDirWholePath = "";
			for (FileDownloadEntity fde : entry.getValue()) {
				topDirWholePath = fde.getTopDiridWholePath();
				currentTotalLen += fde.getDownlength();
				totalFileLen += fde.getFilelen();
				isLoading = fde.getIsloading();
				if (Constants.isloading_yes == isLoading) {
					isLoading = Constants.isloading_yes;
				} else if (Constants.isloading_no == isLoading) {
					isLoading = Constants.isloading_no;
				}
				if (fde.getLoadover() == Constants.loadover_no) {
					isloadover = Constants.loadover_no;
				}
			}
			Log.i("currentTotalLen", "---------------------" + currentTotalLen);
			Log.i("totalFileLen", "---------------------" + totalFileLen);
			createProgressBar(style_download_dir, topDirWholePath, dirid,
					totalFileLen, currentTotalLen, isloadover, isLoading);
		}
	}

	// 创建单个文件上传的进度条
	public void uploadDynicCreateProgressBarByFile(
			List<FileUploadEntity> fileUploadTasks) {
		// 遍历数据库中任务
		for (FileUploadEntity enty : fileUploadTasks) {
			String fileOrDirName = (new File(enty.getWholePath())).getName();
			int isloadover = FileUploadService.isloading_no;
			if (enty.getFileState() == FileUploadEntity.upload_over) {
				isloadover = FileUploadEntity.upload_over;
			}
			if (TAG_FLAG) {
				Log.d(TAG, "the enty.getIsloading() is ================== "
						+ enty.getIsloading());
			}
			createProgressBar(style_upload_file, fileOrDirName,
					enty.getWholePath(), enty.getFilelen(),
					enty.getStartIndex(), isloadover, enty.getIsloading());
		}
	}

	// 创建文件夹上传的进度条
	public void uploadDynicCreateProgressBarByDir(
			Map<String, List<FileUploadEntity>> dirUploadTasks) {
		Set<Map.Entry<String, List<FileUploadEntity>>> dirTasks = dirUploadTasks
				.entrySet();
		for (Map.Entry<String, List<FileUploadEntity>> dirTask : dirTasks) {
			String localTopDirWholePath = dirTask.getKey();
			int pbMaxLen = 0;
			int pbDownLoadLen = 0;
			int loadover = FileUploadEntity.upload_over;
			int isLoading = 0;
			for (FileUploadEntity fue : dirTask.getValue()) {
				pbMaxLen += fue.getFilelen();
				pbDownLoadLen += fue.getStartIndex();
				isLoading = fue.getIsloading();
				if (Constants.isloading_yes == isLoading) {
					isLoading = Constants.isloading_yes;
				} else if (Constants.isloading_no == isLoading) {
					isLoading = Constants.isloading_no;
				}
				if (fue.getFileState() != FileUploadEntity.upload_over) {
					loadover = FileUploadService.isloading_no;
				}
			}
			createProgressBar(style_upload_dir, localTopDirWholePath,
					localTopDirWholePath, pbMaxLen, pbDownLoadLen, loadover,
					isLoading);
		}
	}

	/**
	 * //构建进度条
	 * 
	 * @param style
	 *            是构建“文件”还是“文件夹”
	 * @param fileOrDirName
	 * @param fileOrDirPath
	 * @param pbMaxLen
	 * @param pbDownLoadLen
	 * @param loadover
	 */
	private void createProgressBar(final int style, final String fileOrDirName,
			final String fileOrDirPath, final int pbMaxLen, int pbDownLoadLen,
			int loadover, final int isLoading) {
		allCancelBtn.setEnabled(true);
		LinearLayout processbarLinearLayout = (LinearLayout) inflater.inflate(
				R.layout.processbar, null);
		final ImageView image = (ImageView) processbarLinearLayout
				.findViewById(R.id.img);
		final TextView uptitle = (TextView) ((LinearLayout) processbarLinearLayout
				.getChildAt(1)).getChildAt(0);// 进度条上面的TextView
		final TextView downtitle = (TextView) ((LinearLayout) processbarLinearLayout
				.getChildAt(1)).getChildAt(2);// 进度条下面的TextView
		final ProgressBar pb = (ProgressBar) ((LinearLayout) processbarLinearLayout
				.getChildAt(1)).getChildAt(1);// 进度条
		final ImageView startLv = (ImageView) ((LinearLayout) processbarLinearLayout
				.getChildAt(2)).getChildAt(0);// 开始按钮
		final ImageView pauseLv = (ImageView) ((LinearLayout) processbarLinearLayout
				.getChildAt(2)).getChildAt(1);// 暂停按钮
		final ImageView deleteTaskLv = (ImageView) ((LinearLayout) processbarLinearLayout
				.getChildAt(2)).getChildAt(2);// 删除按钮

		initDownTitleText(style, downtitle, fileOrDirPath);
		sortedFileList(style, fileOrDirName, image);

		if (style == style_download_file || style == style_download_dir) {
			uptitle.setText(fileOrDirName
					+ getString(R.string.download_loading));
		} else if (style == style_upload_file || style == style_upload_dir) {
			uptitle.setText(fileOrDirName + getString(R.string.upload_loading));
		}

		// 初始化进度条状态
		pb.setMax(pbMaxLen);
		pb.setProgress(pbDownLoadLen);

		makeTheReferenceBetweenUIAndThread(style, fileOrDirPath, pb, downtitle);

		startLv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				v.setVisibility(View.GONE);// 隐藏开始按钮
				pauseLv.setVisibility(View.VISIBLE);// 显示暂停按钮
				switch (style) {
				case style_download_file:
					uptitle.setText(fileOrDirName
							+ getString(R.string.download_loading));
					mFileSyncService.startDownLoadThreadByFile(fileOrDirPath,
							pb, downtitle, pbMaxLen);
					break;
				case style_download_dir:
					uptitle.setText(fileOrDirName
							+ getString(R.string.download_loading));
					mFileSyncService.startDownLoadThreadByDir(fileOrDirPath,
							pb, downtitle, pbMaxLen);
					break;
				case style_upload_file:
					uptitle.setText(fileOrDirName
							+ getString(R.string.upload_loading));
					mFileSyncService.startUpload(fileOrDirPath, pb, downtitle,
							pbMaxLen);
					break;
				case style_upload_dir:
					uptitle.setText(fileOrDirName
							+ getString(R.string.upload_loading));
					mFileSyncService.startDirUpload(fileOrDirPath, pb,
							downtitle, pbMaxLen);
					break;
				default:
					break;
				}
			}
		});
		pauseLv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				v.setVisibility(View.GONE);// 隐藏开始按钮
				startLv.setVisibility(View.VISIBLE);// 显示暂停按钮
				switch (style) {
				case style_download_file:
					uptitle.setText(fileOrDirName
							+ getString(R.string.loading_pause));
					mFileSyncService.pauseDownLoadFileThread(fileOrDirPath);
					break;
				case style_download_dir:
					uptitle.setText(fileOrDirName
							+ getString(R.string.loading_pause));
					mFileSyncService.pauseDownLoadDirThread(fileOrDirPath);
					break;
				case style_upload_file:
					uptitle.setText(fileOrDirName
							+ getString(R.string.loading_pause));
					mFileSyncService.pauseUpload(fileOrDirPath);
					break;
				case style_upload_dir:
					uptitle.setText(fileOrDirName
							+ getString(R.string.loading_pause));
					mFileSyncService.pauseDirUpload(fileOrDirPath);
					break;
				default:
					break;
				}
			}
		});
		deleteTaskLv.setOnClickListener(new OnClickListener() {
			// @Override
			public void onClick(View v) {
				switch (style) {
				case style_download_file:
					mFileSyncService.destroyFileDownLoadThread(fileOrDirPath);
					break;
				case style_download_dir:
					mFileSyncService.destroyDirDownLoadThread(fileOrDirPath);
					break;
				case style_upload_file:
					mFileSyncService.destoryFileTask(fileOrDirPath);
					break;
				case style_upload_dir:
					mFileSyncService.destoryDirTask(fileOrDirPath);
					break;
				default:
					break;
				}
				downloadcontainer.removeAllViews();
				dynicCreateProgressBar();
			}
		});
		View line = new View(this);// 一条直线
		line.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, 1));
		line.setBackgroundResource(android.R.drawable.divider_horizontal_dark);
		downloadcontainer.addView(processbarLinearLayout);
		downloadcontainer.addView(line);
		fstes.put(fileOrDirPath, new ForStartTaskEntity(startLv, pauseLv,
				fileOrDirPath, pb, style, downtitle, pbMaxLen));

		if (TAG_FLAG) {
			Log.d(TAG, "the down over is ================== "
					+ mFileSyncService.isDownLoadOver(fileOrDirPath));
			Log.d(TAG,
					"the up over is ================== "
							+ mFileSyncService.isUpLoadOver(fileOrDirPath));
		}

		if (style_download_file == style || style_download_dir == style) {
			if (Constants.isloading_yes == isLoading) {
				uptitle.setText(fileOrDirName
						+ getString(R.string.download_loading));
				startLv.setVisibility(View.GONE);
				pauseLv.setVisibility(View.VISIBLE);
			}
			if (Constants.isloading_no == isLoading) {
				uptitle.setText(fileOrDirName
						+ getString(R.string.loading_pause));
				startLv.setVisibility(View.VISIBLE);
				pauseLv.setVisibility(View.GONE);
			}
			if (Constants.isloading_yes == loadover) {
				uptitle.setText(fileOrDirName + "\n"
						+ getString(R.string.download_finish));
				pb.setVisibility(View.GONE);
				runOnUi(pauseLv);
				downtitle.setVisibility(View.GONE);
				startLv.setVisibility(View.GONE);
			}
		}
		if (style_upload_file == style || style_upload_dir == style) {
			if (Constants.isloading_yes == isLoading) {
				uptitle.setText(fileOrDirName
						+ getString(R.string.upload_loading));
				startLv.setVisibility(View.GONE);
				pauseLv.setVisibility(View.VISIBLE);
			}
			if (Constants.isloading_no == isLoading) {
				uptitle.setText(fileOrDirName
						+ getString(R.string.loading_pause));
				startLv.setVisibility(View.VISIBLE);
				pauseLv.setVisibility(View.GONE);
			}
			if (2 == loadover) {
				uptitle.setText(fileOrDirName + "\n"
						+ getString(R.string.upload_finish));
				pb.setVisibility(View.GONE);
				runOnUi(pauseLv);
				downtitle.setVisibility(View.GONE);
				startLv.setVisibility(View.GONE);
			}
		}
	}

	
	//add by gaoge 2011-04-26,let the backgroup upload or download thread to control the UI 
	private void makeTheReferenceBetweenUIAndThread(final int style,String fileOrDirPath,ProgressBar pb,TextView downtitle){
		File file = new File(fileOrDirPath);
		for(int i=0;i<5;i++){
			Log.d(TAG,"###########  fileOrDirPath is: " + fileOrDirPath + ",isFile() " + file.isFile());
		}
		if(style_download_file == style){
			DownLoadThread thread = downLoadServer.getDownloadThread(fileOrDirPath);
			
			if(null != thread){
				thread.setmProgressBar(pb);
				thread.setTv_percent(downtitle);
			}
		}
		else if(style_download_dir == style){
			List<DownLoadThread> threads = downLoadServer.getDownloadDirThreads(fileOrDirPath);
			int dirTotalLen = getDirAlreadyDownLength(fileOrDirPath);
			if(null != threads){
				TotalFilelenPreDir mulFileTotalLen =DownLoadServer.getInstance(this).getNewTotalFilelenPreDir(dirTotalLen,pb, downtitle);
				//add by gaoge 2011-04-26
				for(int i=0;i<threads.size();i++){
					threads.get(i).setTotalFilelenPreDir(mulFileTotalLen);
				}
			}
		}
		else if(style_upload_file == style){
			UploadThread thread = uploadServer.getUploadThread(fileOrDirPath);
			for(int i=0;i<5;i++){
				Log.d(TAG,"###########  UploadThread thread == null: " + (null == thread));
			}
			if(null != thread){
				thread.setmProgressBar(pb);
				thread.setTv_percent(downtitle);
			}
		}
		else if(style_upload_dir == style){
			List<UploadThread> threads = uploadServer.getUploadDirThreads(fileOrDirPath);
			int dirTotalLen = getDirAlreadyUploadLength(fileOrDirPath);
			if(null != threads){
				UploadServer.TotalFilelenPreDir mulFileTotalLen =UploadServer.getInstance(this).getNewTotalFilelenPreDir(dirTotalLen,pb, downtitle);
				//add by gaoge 2011-04-26
				for(int i=0;i<threads.size();i++){
					threads.get(i).setTotalFilelenPreDir(mulFileTotalLen);
				}
			}
		}
		
	}
	
	private int getDirAlreadyDownLength(String dirpath){
		int totalAlreadyLen = 0;
		List<FileDownloadEntity> entrys = downLoadServer.getDirLoadTask(dirpath);
		for(int i=0;i<entrys.size();i++){
			totalAlreadyLen += entrys.get(i).getDownlength();
		}
		return totalAlreadyLen;
		
	}
	
	private int getDirAlreadyUploadLength(String dirpath){
		int totalAlreadyLen = 0;
		List<FileUploadEntity> entrys = uploadServer.getDirTask(dirpath);
		for(int i=0;i<entrys.size();i++){
			totalAlreadyLen += entrys.get(i).getStartIndex();
		}
		return totalAlreadyLen;
		
	}
	
	private void runOnUi(final ImageView pauseLv) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				pauseLv.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void onTitleIconClick() {
		if (TAG_FLAG)
			Log.e(TAG, "==> onTitleIconClick===projectState==" + projectState);
		Intent intent = new Intent();
		if (projectState != null) {
			if (projectState.equals(DirDefines.mDir1)) {
				intent.setClass(TaskManagerActivity.this,
						com.lenovo.leos.filebrowser.ui.MainActivity.class);
			} else if (projectState.equals(DirDefines.mDir3)) {
				intent.setClass(TaskManagerActivity.this, LenovoActivity.class);
			}
			intent.putExtra("projectState", projectState);
			startActivity(intent);
		}
	}

	// add drawable icon
	HashMap<String, Drawable> mMimeIconMap;

	private Drawable getDrawableForMimetype(String mimetype) {
		if (TAG_FLAG) {
			Log.e(TAG, "==> getDrawableForMimetype");
		}
		Drawable icon = null;
		if (mMimeIconMap == null) {
			mMimeIconMap = new HashMap<String, Drawable>();
		}

		icon = mMimeIconMap.get(mimetype);
		if (TAG_FLAG) {
			// Log.e(TAG, "the icon is ---------------" + icon);
		}
		if (icon == null) {
			PackageManager pm = TaskManagerActivity.this.getPackageManager();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromParts("file", "", null), mimetype);

			List<ResolveInfo> lri = pm.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			List<ResolveInfo> lriRe = pm.queryBroadcastReceivers(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			if (lri != null && lri.size() > 0) {
				icon = lri.get(0).loadIcon(pm);
			} else if (lriRe != null && lriRe.size() > 0) {
				icon = lriRe.get(0).loadIcon(pm);
			}

			if (icon != null) {
				mMimeIconMap.put(mimetype, icon);
			} else if (mimetype.equals(ZIP_MIMETYPE)) {
				icon = TaskManagerActivity.this.getResources().getDrawable(
						R.drawable.zip);
				mMimeIconMap.put(mimetype, icon);
			} else {
				icon = TaskManagerActivity.this.getResources().getDrawable(
						R.drawable.icon_unknown_file);
				mMimeIconMap.put(mimetype, icon);
			}
		}

		return icon;
	}

	/**
	 * @param style
	 *            文件还是文件夹
	 * @param fileOrDirName
	 *            文件或文件夹的名称
	 * @param image
	 */
	private void sortedFileList(int style, String fileOrDirName, ImageView image) {
		if (TAG_FLAG) {
			Log.e(TAG, "==> sortedFileList");
		}
		if (fileOrDirName == null) {
			return;
		}

		Drawable currentUsrIcon = TaskManagerActivity.this.getResources()
				.getDrawable(R.drawable.icon_default_folder);
		Drawable fileIcon = null;

		if (style_download_dir == style || style_upload_dir == style) {
			image.setBackgroundDrawable(currentUsrIcon);
		} else {
			String mimetype = mMimeTypes.getMimeType(fileOrDirName
					.toLowerCase());
			if (TAG_FLAG) {
				Log.d(TAG, "the fileOrDirName is -----------" + fileOrDirName);
				Log.d(TAG, "the mimetype is -----------" + mimetype);
			}
			if (mimetype == null) {
				if (FileUtil.getExtension(fileOrDirName).equals(".p12")) {
					fileIcon = TaskManagerActivity.this.getResources()
							.getDrawable(R.drawable.ic_menu_login);
				} else {
					fileIcon = TaskManagerActivity.this.getResources()
							.getDrawable(R.drawable.icon_unknown_file);
				}
			} else {
				fileIcon = getDrawableForMimetype(mimetype);
				image.setBackgroundDrawable(fileIcon);
			}
		}
	}

	private void initMimeTypes() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> initMimeTypes");
		}
		if (mMimeTypes == null) {
			MimeTypeParser mtp = new MimeTypeParser();

			// XmlResourceParser in = getResources().getXml(
			// com.android.internal.R.xml.mimetypes);
			XmlResourceParser in = TaskManagerActivity.this.getResources()
					.getXml(R.xml.mimetypes);
			try {
				mMimeTypes = mtp.fromXmlResource(in);
			} catch (XmlPullParserException e) {
				if (TAG_FLAG)
					Log.e(TAG,
							"************************** XmlPullParserException",
							e);
				throw new RuntimeException(
						"*************************** XmlPullParserException");
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.e(TAG, "************************** IOException", e);
				throw new RuntimeException(
						"************************** IOException", e);
			}
		}
	}

	// end

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.allCancelBtn:
			// 调用全部清除接口
			deleteAllLoadTask();
			break;

		default:
			break;
		}
	}

	private void deleteAllLoadTask() {
		// 从数据库中得到所有的下载任务
		List<FileDownloadEntity> fileTasks = mFileSyncService.getFilesLoadTask();
		// 从数据库中得到所有的文件夹下载任务
		Map<String, List<FileDownloadEntity>> dirTasks = mFileSyncService
				.getDirsLoadTask();
		// 从数据库中得到所有的文件夹和文件上传任务
		AllUploadTaskEntity allUploadTask = mFileSyncService.getAllTask();
		this.mFileSyncService.destoryAllTask(fileTasks, dirTasks);
		this.mFileSyncService.destoryAllTask(allUploadTask);
		downloadcontainer.removeAllViews();
	}

	DecimalFormat df = new DecimalFormat("###");

	/**
	 * add by gaoge to set the text value when this activity onResume
	 * 
	 * @param style
	 * @param tv_percent
	 * @param path
	 */
	public void initDownTitleText(int style, TextView tv_percent, String path) {
		if (style_download_dir == style) {
			List<FileDownloadEntity> entities = mFileSyncService
					.getDirLoadTask(path);
			int totalDownLoadLen = 0;
			int totalFileLen = 0;
			for (int i = 0; i < entities.size(); i++) {
				totalDownLoadLen += entities.get(i).getDownlength();
				totalFileLen += entities.get(i).getFilelen();
			}

			double percent = (double) totalDownLoadLen / (double) totalFileLen
					* 100;
			String value = df.format(percent) + "%";
			String down_and_all = " "
					+ DownLoadThread.transferSize(totalDownLoadLen) + "/"
					+ DownLoadThread.transferSize(totalFileLen);
			tv_percent.setText(value + down_and_all);

		} else if (style_download_file == style) {
			FileDownloadEntity entity = mFileSyncService.getFileLoadTask(path);
			double percent = (double) entity.getDownlength()
					/ (double) entity.getFilelen() * 100;
			String value = df.format(percent) + "%";
			String down_and_all = " "
					+ DownLoadThread.transferSize(entity.getDownlength()) + "/"
					+ DownLoadThread.transferSize(entity.getFilelen());
			tv_percent.setText(value + down_and_all);
		} else if (style_upload_file == style) {
			FileUploadEntity entity = mFileSyncService.getFileTask(path);
			double percent = (double) entity.getStartIndex()
					/ (double) entity.getFilelen() * 100;
			String value = df.format(percent) + "%";
			String down_and_all = " "
					+ DownLoadThread.transferSize(entity.getStartIndex()) + "/"
					+ DownLoadThread.transferSize(entity.getFilelen());
			tv_percent.setText(value + down_and_all);

		} else if (style_upload_dir == style) {
			List<FileUploadEntity> entities = mFileSyncService.getDirTask(path);
			int totalDownLoadLen = 0;
			int totalFileLen = 0;
			for (int i = 0; i < entities.size(); i++) {
				totalDownLoadLen += entities.get(i).getStartIndex();
				totalFileLen += entities.get(i).getFilelen();
			}

			double percent = (double) totalDownLoadLen / (double) totalFileLen
					* 100;
			String value = df.format(percent) + "%";
			String down_and_all = " "
					+ DownLoadThread.transferSize(totalDownLoadLen) + "/"
					+ DownLoadThread.transferSize(totalFileLen);
			tv_percent.setText(value + down_and_all);
		}
	}

}